//
//  NetWorkTool.m
//  QYer
//
//  Created by lanou on 16/8/5.
//  Copyright © 2016年 CaiZhuYu. All rights reserved.
//

#import "NetWorkTool.h"

@implementation NetWorkTool

+ (void)requstWithType:(requestType)type URLString:(NSString *)urlString parameter:(NSDictionary *)parameterDic callBack:(void (^)(NSData *, NSError *))callBack {
    
    NSURL *URL = [NSURL URLWithString:urlString];
    if (URL == nil) {
        NSString *utf8String = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
        URL = [NSURL URLWithString:utf8String];
    }
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    if (type == POST) {
        [request setHTTPMethod:@"POST"];
        if (parameterDic == nil) {
            NSLog(@"请求参数未设置");
        } else {
            //设置请求参数
            [request setHTTPBody:[NetWorkTool dataForDic:parameterDic]];
        }
    }
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        callBack(data, error);
    }] resume];
    
}


//将字典转换为Data
+ (NSData *)dataForDic:(NSDictionary *)dic{
    //创建一个数组
    NSMutableArray *arr = [NSMutableArray array];
    
    //便利所有的key
    for (NSString *key in dic) {
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        //将每次的到的键值对存到数组
        [arr addObject:str];
    }
    //用&符号将所有的键值对连接
    NSString *parameterStr = [arr componentsJoinedByString:@"&"];
    NSLog(@"%@",parameterStr);
    return  [parameterStr dataUsingEncoding:NSUTF8StringEncoding];
}






















@end
